//桌面来管理牌，初始化，创建，操作牌型

package model

import (
	"errors"
	"math/rand"
	"time"
)

type Deck struct {
	Cards []CardsData
}

/*
获取一副新牌
参数，表示生成多少副牌
*/
func (d *Deck) Initialize(count, pairs int) error {
	if pairs <= 0 || count <= 0 {
		return nil
	}
	d.Cards = nil
	for k := 0; k < pairs; k++ {
		for i := 1; i <= count; i++ {
			d.Cards = append(d.Cards, *NewCardsData(i))
		}
	}
	// d.Shuffle() //洗牌
	return nil
}

// 洗牌
func (d *Deck) Shuffle() (err error) {
	vals := d.Cards
	r := rand.New(rand.NewSource(time.Now().Unix()))
	for len(vals) > 0 {
		n := len(vals)         //数组中有多少个元素
		randIndex := r.Intn(n) //随机生成一个key
		vals[n-1], vals[randIndex] = vals[randIndex], vals[n-1]
		vals = vals[:n-1]
	}
	return nil
}

/*
参数1:发牌个数
[并返回[]牌组切片]
*/
func (d *Deck) Draw(count int) (cards []CardsData, err error) {
	if count > len(d.Cards) {
		return nil, errors.New("桌面没有足够的牌分发")
	}
	hand := d.Cards[0:count]
	d.Cards = d.Cards[count:]
	return hand, nil
}

// 返回桌面牌组中剩余的牌数
func (d *Deck) CardsLeft() int {
	return len(d.Cards)
}

/*
参数1:true=正序小到大,false=倒序大到小
[一维]牌值点数+花色排序
*/
func (d *Deck) SortByCardsPoint(b bool) error {
	SortByCardsPoint(d.Cards, b)
	return nil
}

/*
拼接牌点数方便显示🃏-♠1...♠13
*/
func (d *Deck) CardsNameConcat() error {
	for k := range d.Cards {
		d.Cards[k].Name = d.Cards[k].CardsNameOnebyOne()
	}
	return nil
}
